import React, {Component} from 'react';

import {
    View,
    StyleSheet,
    Image,
    Text,
    ListView,
    RefreshControl,
    DeviceEventEmitter,
    Navigator,
} from 'react-native';
import ScrollableTabView,{DefaultTabBar} from 'react-native-scrollable-tab-view';
import NavigationBar from '../common/NavigationBar';
import DataRepository,{FLAG_STORAGE} from '../expand/dao/DataRepository';
import RepositoryCell from '../common/RepositoryCell';
import LanguageDao,{FLAG_LANGUAGE} from '../expand/dao/LanguageDao';
import RepositoryDetail from './RepositoryDetail'
const URL='https://api.github.com/search/repositories?q=';
const QUERY_STR='&SORT=stars';

export default class PopularPage extends Component {
    constructor(props) {
        super(props);
        this.languageDao=new LanguageDao(FLAG_LANGUAGE.flag_key);
        this.state={
            languages:[],
        }
    }
    componentDidMount() {
      this.loadData();
    }
    loadData() {
        this.languageDao.fetch()
            .then(result=>{
                this.setState({
                    languages:result
                })
            })
            .catch(error=>{
                console.log(error);
            })
    }
    render() {
        let content=this.state.languages.length>0?
                <ScrollableTabView
                tabBarUnderlineStyle={{backgroundColor:"white",height:2,flex:1}}
                tabBarInactiveTextColor="mintcream"
                tabBarActiveTextColor="white"
                ref="scrollableTabView"
                tabBarBackgroundColor="#2196f3"
                initialPage={0}
                renderTabBar={()=><DefaultTabBar style={{height:60}}
                                                    tabStyle={{height:50}}/>}
                >
                {this.state.languages.map((result,i,arr)=>{
                    let lan=arr[i];
                    return lan.checked? <PopularTab key={i} tabLabel={lan.name} {...this.props}/>:null;
                })}
               </ScrollableTabView>:null;
        return <View style={styles.container}>
                 <NavigationBar
                     title="最热"
                     style={{backgroundColor: '#2196F3'}}
                 />
                 {content}
            </View>        
    }
}
//分栏组件
class PopularTab extends Component{
    constructor(props) {
        super(props);
        this.dataRepository=new DataRepository(FLAG_STORAGE.flag_popular);
        this.state={
            result:'',
            dataSource:new ListView.DataSource({rowHasChanged:(r1,r2)=>r1!==r2}),
            isloading:false,
        }
    }
    componentDidMount() {
        this.loadData();
    }
    loadData() {
        this.setState({
            isloading:true
        })
        let url=URL+this.props.tabLabel+QUERY_STR;
        this.dataRepository
            .fetchRepository(url)
            .then(result=>{
                let items=result&&result.items?result.items:result?result:[];
                this.setState({
                    dataSource:this.state.dataSource.cloneWithRows(items),
                    isloading:false,
                })
              
                //判断过时
                if(result&&result.update_date&&!this.dataRepository.checkData(result.update_date)){
                    DeviceEventEmitter.emit('showToast','数据过时');
                    return this.dataRepository.fetchNetRepository(url);
                }else{
                    DeviceEventEmitter.emit('showToast','显示缓存数据');
                }
            })
            .then(items=>{
                if(!items||items.length===0)return;
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(items),
                });
                DeviceEventEmitter.emit('showToast','显示网络数据');
            })
            .catch(error=>{      
                    console.log(error);
                    this.setState({
                        isloading:false,
                    })
                })
            }
    onSelect(item) {
            this.props.navigator.push({
                component:RepositoryDetail,
                params:{
                    item:item,
                    ...this.props
                }
            })
    }
    renderRow(data){
        return <RepositoryCell  
            onSelect={()=>this.onSelect(data)}
            key={data.id}
            data={data}/>
    }
    render() {
        return <View style={{flex:1}}>
                <ListView
                dataSource={this.state.dataSource}
                renderRow={(data) => this.renderRow(data)}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isloading}
                        onRefresh={()=>this.loadData()}  
                        colors={['#2196F3']}
                        tintColor={'#2196F3'}
                        title={'wait...'}
                        titleColor={'#2196F3'}                  
                    />}
                />
            </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    tips:{
        fontSize:20,
    }
})